<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      label-position="left"
      label-width="0px"
      class="login-form position-middle-center"
    >
      <h3 class="title">安心电管家</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="用户名" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          maxlength="20"
          @keyup.enter.native="handleLogin"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 60%"
          maxlength="4"
          @keyup.enter.native="handleLogin"
        />
        <div class="login-code pointer">
          <img :src="codeUrl" @click="getCode">
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
      <div class="pb20 clear">

        <router-link class="fl c-999 fz14" to="/forgot">忘记密码?</router-link>
        <router-link class="fr c-main" to="/register">注册</router-link>
      </div>
    </el-form>
  </div>
</template>

<script>
import SIdentify from "./modul/identify";
import { _login, _vCode, _userLevel } from "@/http/ajax";
import * as MDZZ from "@/http/reg";
export default {
  components: {
    SIdentify
  },
  name: "Login",
  data() {
     const validUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("用户名不能为空"));
      } else if (!MDZZ.shuziyingwen(value)) {
        callback(new Error("用户名格式不对（只能是数字、字母组成）"));
      } else {
        callback();
      }
    };
     const validPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else if (!MDZZ.shuziyingwen(value)) {
        callback(new Error("密码格式不对（只能是数字、字母组成）"));
      } else {
        callback();
      }
    };
     const validCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("验证码不能为空"));
      } else if (!MDZZ.shuziyingwen(value)) {
        callback(new Error("验证码格式不对"));
      } else {
        callback();
      }
    };
    return {
      codeUrl: "",
      loginForm: {
        username:  localStorage.username||"",
        password:  localStorage.password||"",
        rememberMe: localStorage.rememberMe?true:false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validUsername }
        ],
        password: [
          { required: true, trigger: "blur", validator: validPass }
        ],
        code: [{ required: true, trigger: "blur", validator: validCode }]
      },
      loading: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    // sessionStorage.removeItem("token");
    // sessionStorage.removeItem("user");
    this.getCode();
  },
  methods: {
     isvalidPhone(str) {
      const reg = /^[0-9a-zA-Z]*$/g;
      return reg.test(str);
    },
     isvalidCode(str) {
      const reg = /^[0-9]*$/g;
      return reg.test(str);
    },
    getCode() {
      _vCode(
        res => {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        },
        err => {}
      );
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        var user = this.loginForm;
        if (valid) {
          this.loading = true;
          let _this = this;
          _login(
            user,
            res => {
              sessionStorage.token = res.token;
              _userLevel(res.user.id, ress => {
                if(this.loginForm.rememberMe){
                  localStorage.username = this.loginForm.username
                  localStorage.password = this.loginForm.password
                  localStorage.rememberMe = this.loginForm.rememberMe
                }else{
                  localStorage.removeItem('username')
                  localStorage.removeItem('password')
                  localStorage.removeItem('rememberMe')
                }
                const roles = ress.roles || [];
                let level = 0,
                  arr = [];
                if (roles.length){
                  roles.forEach(e => {
                    arr.push(e.level)
                  })
                  level = Math.max.apply(null, arr)
                }
                sessionStorage.user = JSON.stringify(ress);
                sessionStorage.level = level
                this.loading = false;
                if(level==5){
                  this.$router.push("/home/list");
                }else if(level == 4 ){
                  this.$router.push("/work/Install");
                }else if(level == 0 ){
                  this.$router.push("/work/Install");
                }else{
                  this.$router.push("/home");
                }
              },errr => {
               
              })
            },
            er => {
              this.getCode();
              this.loading = false;
            }
          );
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  position: relative;
  height: 100%;
  background-image: url(https://docs-1255840532.cos.ap-shanghai.myqcloud.com/3968.jpg);
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 380px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  display: inline-block;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
